package com.broad.commerce.code.base;

import com.broad.commerce.code.models.EntityModuleDTO;
import com.broad.commerce.code.modules.jdbc.EntityField;
import com.broad.commerce.code.modules.jdbc.EntityModule;
import com.broad.commerce.common.utils.io.BeanUtils;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author stephen
 * @version V1.0
 * @date 2022-02-18 15:44
 * @description: EntityModuleCreator
 **/
public class EntityModuleCreator {

	public static EntityModule createEntityModule(EntityModuleDTO entityModuleDTO) {
		EntityModule entityModule = BeanUtils.parse(entityModuleDTO, EntityModule.class);
		List<EntityField> entityFields = Lists.newArrayList();
		if (!CollectionUtils.isEmpty(entityModuleDTO.getDatas())) {
			entityModuleDTO.getDatas().forEach(entityFieldDTO -> {
				String filedTypeName = entityFieldDTO.getFieldTypeName();
				Class<?> fieldType = null;
				try {
					fieldType = Class.forName(filedTypeName);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				String fieldName = entityFieldDTO.getFieldName();
				String fieldComment = entityFieldDTO.getFieldComment();
				Boolean required = entityFieldDTO.getRequired() != null && entityFieldDTO.getRequired();
				Object defaultValue = required ? entityFieldDTO.getDefaultValue() : null;
				Integer length = entityFieldDTO.getLength() != null && entityFieldDTO.getLength() > 0 ? entityFieldDTO.getLength() : 0;
				entityFields.add(new EntityField(fieldName, fieldType, fieldComment, required, defaultValue, length));
			});
		}
		entityModule.setEntityFields(entityFields);
		return entityModule;
	}
}
